#!/usr/bin/env python
#coding=utf-8

import json
import time
import random
from lottery.view import mysql_util

def GET():
    try:
        conn = mysql_util.getconn()
        conn.execute('select * from prize')
        prizes = conn.fetchall()
        fp = prizes[0]
        begintime = fp[2]
        print (" -_- 1. begintime= ", begintime)
        datadict = {}
        winners = []
        if begintime == "":
            print (" -_- 2.Game does not start yet.")
            datadict['winners'] = winners
            datadict['result'] = 'false'
            datadict['msg'] = '游戏还未开始'
        else:
            before = int(time.mktime(time.strptime(begintime,'%Y-%m-%d %H:%M:%S')))
            now = int(time.time())
            conn.execute("select * from bulletgift where remaining>0 order by importance desc")
            gifts = conn.fetchall()
            print ("-_- 3. now = ", now)
            print ("-_- 4. before = ", before)
            if(len(gifts) == 0):
                print (" -_- 5. Game is done.")
                datadict['winners'] = winners
                datadict['result'] = 'false'
                datadict['msg'] = '游戏已经束'
            else:
                giftCandidates = []
                for gift in gifts:
                    giftCandidates.append(gift)
                if((now - before)/60 > 10):
                    print (" -_- 6. Game in 10 mins. genreate new winners")
                    nowtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                    print (" -_- 7. nowtime= ", nowtime)
                    bullets = conn.execute("select mobile from sign ts where exists(select * from bullet tb where tb.mobile = ts.mobile and tb.mobile is not null and tb.mobile <> '' and tb.uptime between '" + begintime + "' and '" + nowtime + "')")
                    mobilelist = []
                    for bullet in bullets:
                        mobilelist.append(bullet.mobile)
                    mobilelist = list(set(mobilelist))
                    generateWiners(mobilelist,giftCandidates,nowtime,conn)
                    conn.update('prize', where="id=1", begintime=nowtime)
                print (" -_- 8. Game return the all winners")
                gifthis = db.query('select * from bulletgifthis order by winat desc')
                print (" -_- 9. Game return the all winners: ", len(gifthis))
                for winner in gifthis:
                    winners.append(winner.winner+" - "+str(winner.giftname))
                #print winners
                datadict = {}
                datadict['winners'] = winners
                datadict['result'] = 'true'
        return json.dumps(datadict, ensure_ascii=False)
    except Exception as e:
        return e.args

def generateWiners(mobilelist, giftCandidates, nowtime, db):
    max = 20
    actualNums = len(mobilelist)
    crtwinners = []
    print ("-_- 7.1 actualNums = ", actualNums)
    for i in range(0, actualNums):
        print ("-_- 7.2 i = ", i)
        if(len(giftCandidates)<=0):
            print ("-_- 7.3 i = gift all sell out.", i)
            break
        if not mobilelist[i]:
            print ("-_- 7.4 i, invalid mobile num: ", i, mobilelist[i])
            continue
        preWinGifts = db.select('bulletgifthis', where="winner = '"+ mobilelist[i] +"'")
        preGifts = []
        for pgift in preWinGifts:
            preGifts.append(pgift)
        if(len(preGifts) >= 2):
            print ("-_- 7.5 i, this mobile num already won twice. ", i, mobilelist[i])
            continue
        gift=randomGift(1,giftCandidates,preGifts)
        if not gift:
            print ("-_- 7.6 i, cannot generate any gift for this mobile after try 10 times. ", i, mobilelist[i])
            continue
        print ("-_- 7.6 win a bullet git ", mobilelist[i], gift.name.encode("utf-8"))
        db.insert('bulletgifthis',winner=mobilelist[i],giftname=gift.name,winat=nowtime, qty=1)
        crtwinners.append(str(mobilelist[i])+" - "+str(gift.name))
        gift.remaining = gift.remaining - 1
        db.update('bulletgift', where="id="+ str(gift.id), remaining=gift.remaining)
        if len(crtwinners) >= max:
            break
    return crtwinners

def randomGift(self,times, giftCandidates, preGifts):
    print ("-_- 7.2.1 random generate gift")
    if len(giftCandidates)<=0:
       print ("-_- 7.2.2 no gift now")
       return ""
    index = random.randint(0,len(giftCandidates)-1)
    if(giftCandidates[index].remaining <= 0):
       print ("-_- 7.2.3 this gift remainig is 0 : ", giftCandidates[index].name.encode("utf-8"))
       del giftCandidates[index]
       return self.randomGift(times, giftCandidates, preGifts)
    if len(preGifts) < 1:
       print ("-_- 7.2.4 first time get bullet gift return , ", giftCandidates[index].name.encode("utf-8"))
       return giftCandidates[index]
    if giftCandidates[index].name.encode("utf-8") != preGifts[0].giftname.encode("utf-8"):
       print ("-_- 7.2.5 second time get different bullet gift return , ", giftCandidates[index].name.encode("utf-8"))
       return giftCandidates[index]
    if times > 10:
       print ("-_- 7.2.6 10 times get same bullet gift return empty ")
       return ""
    print ("-_- 7.2.7 try next time for this guy.")
    return self.randomGift(times+1, giftCandidates, preGifts)
